﻿public class ListNode2
{
    public int val;
    public ListNode2 next;
    public ListNode2(int x) { val = x; }
}

public class Solution160
{
    public ListNode2 GetIntersectionNode(ListNode2 headA, ListNode2 headB)
    {
        // 在这里实现 GetIntersectionNode() 的逻辑
        ListNode2 curA = headA;
        ListNode2 curB = headB;

        while (curA != null && curB != null)
        {
            curA = curA.next;
            curB = curB.next;

        }
        ListNode2 preA = headA;
        ListNode2 preB = headB;


        while (curA != null)
        {

            curA = curA.next;
            preA = preA.next;


        }
        while (curB != null)
        {
            curB = curB.next;
            preB = preB.next;
        }

        while (preA != preB)
        {

            preA = preA.next;
            preB = preB.next;
        }





        return preA;
    }
}

class Program160
{
    static void Main160(string[] args)
    {
        Solution160 solution = new();

        // 创建链表A
        ListNode2 headA = new ListNode2(1);
        ListNode2 nodeA2 = new ListNode2(2);
        ListNode2 nodeA3 = new ListNode2(3);
        headA.next = nodeA2;
        nodeA2.next = nodeA3;

        // 创建链表B
        ListNode2 headB = new ListNode2(4);
        ListNode2 nodeB2 = new ListNode2(5);
        headB.next = nodeB2;
        nodeB2.next = nodeA2; // 链表B的尾部连接到链表A的节点2

        ListNode2 intersectionNode = solution.GetIntersectionNode(headA, headB);
        if (intersectionNode != null)
        {
            Console.WriteLine("Intersection node value: " + intersectionNode.val);
        }
        else
        {
            Console.WriteLine("No intersection node found.");
        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
}